import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:scroll_to_index/scroll_to_index.dart';

import '../../pojo/ImPojo.dart';
import '../../util/ImConstant.dart';
import '../bloc/SelectUsersCubit.dart';
import 'component/UserIconView.dart';
import 'component/cell/UserItemSelectView.dart';
import 'component/SearchView.dart';

class SelectUsersView extends StatefulWidget {

  final Widget? groupWidget;

  const SelectUsersView({ this.groupWidget, super.key});

  @override
  State<StatefulWidget> createState() => _SelectUsersState();
}

class _SelectUsersState extends State<SelectUsersView> {

  late AutoScrollController _userScrollController;
  late AutoScrollController _selectedUserScrollController;

  @override
  void initState() {
    _userScrollController = AutoScrollController(
        viewportBoundaryGetter: () => Rect.fromLTRB(0, 0, 0, MediaQuery.of(context).padding.bottom),
        axis: Axis.vertical);

    _selectedUserScrollController = AutoScrollController(
        viewportBoundaryGetter: () => Rect.fromLTRB(0, 0, 0, MediaQuery.of(context).padding.bottom),
        axis: Axis.vertical);

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var selectUsersCubit = context.watch<SelectUsersCubit>();
    var state = selectUsersCubit.state;
    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.only(left: 10, right: 10, top: 10),
          child: SearchView<SelectUsersCubit>(
            prefix: state.selectedUsers.isNotEmpty ? _buildSelectedUserList(state) : null,
            searchHandler: _doSearch,
            param: selectUsersCubit,
          ),
        ),
        const SizedBox(
          height: 10,
        ),
        Expanded(child: Container(
          color: ImConstant.IM_RESERVE_BACKGROUND_COLOR,
          child: _buildBody(context, selectUsersCubit),
        )),
      ],
    );
  }

  Widget _buildBody(BuildContext context, SelectUsersCubit selectUsersCubit) {
    if (selectUsersCubit.state.search == '') {
      return _buildUserContainer(selectUsersCubit);
    } else {
      return _buildSearchResult(selectUsersCubit);
    }
  }

  Widget _buildUserContainer(SelectUsersCubit selectUsersCubit) {
    return Stack(
      children: [
        _buildUserList(selectUsersCubit),
        Positioned(
          right: 10,
          child: Center(
            child: Column(
                children: selectUsersCubit.state.letters
                    .asMap()
                    .map<int, Widget>((index, letter) => MapEntry(
                    index,
                    GestureDetector(
                      child: _buildLetter(letter),
                      onTap: () => _jumpToUser(selectUsersCubit.state.letters, selectUsersCubit.state.letterSizeMap, letter),
                    )))
                    .values
                    .toList()),
          ),
        )
      ],
    );
  }

  Widget _buildSearchResult(SelectUsersCubit selectUsersCubit) {
    List<ImUser> showUsers = selectUsersCubit.state.filterUsers;
    return ListView.builder(
      itemBuilder: (BuildContext context, int index) {
        return UserItemSelectView(user: showUsers.elementAt(index), isSelected: selectUsersCubit.state
            .existedUserIdSet.contains(showUsers.elementAt(index).userId),);
      },
      itemCount: showUsers.length,
    );
  }

  Widget _buildUserList(SelectUsersCubit selectUsersCubit) {
    List<ImUser> allUsers = selectUsersCubit.state.allUsers;
    var groupWidget = widget.groupWidget;
    return CustomScrollView(
      slivers: [
        if (groupWidget != null)
          SliverToBoxAdapter(
            child: groupWidget,
          ),
        SliverList.builder(
          itemBuilder: (BuildContext context, int index) {
            var preUser = index > 0 ? allUsers.elementAt(index - 1) : null;
            var user = allUsers.elementAt(index);
            Set<String> existedUserIdSet = selectUsersCubit.state.existedUserIdSet;
            return AutoScrollTag(
                key: ValueKey(index),
                controller: _userScrollController,
                index: index,
                child: UserItemSelectView(user: user,
                  preUser: preUser,
                  selectedUserScrollController: _selectedUserScrollController,
                  isSelected: existedUserIdSet.contains(user.userId),
                )

            );
          },
          itemCount: allUsers.length,
        ),
      ],
      controller: _userScrollController,
    );
  }

  Widget _buildLetter(String letter) {
    return Container(
      width: 20,
      padding: const EdgeInsets.only(left: 5, right: 10, top: 2, bottom: 2),
      decoration: const ShapeDecoration(
        shape: CircleBorder(),
        color: Colors.black12, // 圆点的颜色
      ),
      child: Center(
        child: Text(
          letter,
          style: const TextStyle(
            color: Colors.black87,
          ),
        ),
      ),
    );
  }

  Widget _buildSelectedUserList(SelectUsersState state) {
    return ConstrainedBox(
      constraints: const BoxConstraints(maxWidth: 33 * 7),
      child: Container(
        width: 30.0 * state.selectedUsers.length + 20.0,
        height: 40,
        margin: const EdgeInsets.only(right: 10),
        child: ListView.builder(
          itemBuilder: (context, index) {
            return AutoScrollTag(
                key: ValueKey(index),
                controller: _selectedUserScrollController,
                index: index,
                child: Container(
                  margin: const EdgeInsets.only(left: 3, top: 3, bottom: 3),
                  decoration: BoxDecoration(
                      border: Border.all(color: ImConstant.IM_MAIN_BACKGROUND_COLOR, width: 1),
                      borderRadius: const BorderRadius.all(Radius.circular(5))),
                  child: GestureDetector(
                    onTap: () async {
                      var uindex = state.allUsers.indexOf(state.selectedUsers[index]);
                      if (uindex >= 0) {
                        await _userScrollController.scrollToIndex(uindex);
                        _userScrollController.highlight(uindex);
                      }
                    },
                    child: UserIconView(user: state.selectedUsers[index], iconSize: 30,),
                  ),
                ));
          },
          physics: const AlwaysScrollableScrollPhysics(),
          controller: _selectedUserScrollController,
          itemCount: state.selectedUsers.length,
          scrollDirection: Axis.horizontal,
        ),
      ),
    );
  }

  @override
  void dispose() {
    _userScrollController.dispose();
    _selectedUserScrollController.dispose();
    super.dispose();
  }

  /// 调整首字母处
  void _jumpToUser(List<String> letters, Map<String, int> letterSizeMap, String letter) async {
    var size = 0;
    print('Current letter0: ${letter}');
    for (var i = 0; i < letters.length; i++) {
      if (letters[i] == letter) {
        break;
      }
      size += letterSizeMap[letters[i]] ?? 0;
    }
    print('Current letter0: ${letter}, $size');
    await _userScrollController.scrollToIndex(size, preferPosition: AutoScrollPosition.begin);
    _userScrollController.highlight(size);
  }

  void _doSearch(dynamic? context1, String searchText) {
    if (context1 == null) return;
    var selectUsersCubit = context1 as SelectUsersCubit;
    selectUsersCubit.add(SelectUsersSearchEvent(searchText));
  }

}